<script lang="ts" setup name="值班日历">
import { ref, reactive, watch, computed, onMounted, nextTick } from "vue";
import dayjs, { Dayjs } from "dayjs";
import ProFrom from "@/components/ProFrom/ProFrom.vue";
import ProTable from "@/components/ProTable";
import { useGlobalStore } from "@/stores";
import { queryFormMap, editFormMap } from "./form";

import { setBaseApi, get, post, del } from "@/api/http";

const { dictionary } = useGlobalStore();

const formatPosition = (val: number, { position }: any) => {
  const res = dictionary.groupPosition.filter(({ value }) => value == position);
  if (!res[0]) return "";
  return res[0].label;
};
const securityStatus = ref(false);

get("/watch/security/getSecurityStatus").then((res: any) => {
  securityStatus.value = res.securityStatus;
});

const detailFormMap = ref(editFormMap);

setBaseApi("/watch/Schedule/");

const response = reactive({
  open: false,
  value: null,
  levelList: [],
  description: "",
});

const openResponse = () => {
  response.open = true;
  get("/watch/response/list").then((list) => {
    response.levelList = list;
    const filterV = list.filter((e) => e.responseStatus == 2);
    if (!filterV[0]) return;
    response.value = filterV[0].id;
    response.description = filterV[0].watchWarning;
  });
};

const resList = dictionary.responseLevel.map((e) => e.label);

const formatLevel = (level: number) => [, ...resList][level];

const handelChangeResponse = () => {
  const id = response.value;
  get("/watch/response/updateStatus", { id, responseStatus: 2 }, "启动").then(
    () => {
      response.open = false;
    }
  );
};

const levelList = dictionary.reponStatus;

const levelLegendtList = [
  {
    label: "应急响应",
    color: "rgb(225, 66, 38)",
  },
].concat(levelList.slice(4, 6) as any);

const queryForm = reactive({});
const querying = ref<boolean>(false);
const queryFormRef = ref<InstanceType<typeof ProFrom>>();

const dutyList = ref<any[]>([]);

const handleQuery = () => {
  queryFormRef.value
    ?.verify()
    .then(async (query: any) => {
      get("list", query, "", querying).then((list) => {
        console.log(list);

        dutyList.value = list.map((e) => ({
          ...e,
          // reponStatus: 3  ,
          reponStatus: e.reponStatus == 7 ? 6 : e.reponStatus, //待定状态改为正常
        }));
      });
    })
    .catch((err: any) => {});
};

onMounted(() => handleQuery());

/**
 * 获取当前日期的值班状况
 * @param day Dayjs日期对象
 */
const getStatus = (day: Dayjs) => {
  const current = dutyList.value.filter(
    // 可将年月日比较改为日期比较 以提升性能
    (duty) => duty.dutyDate == day.format("YYYY-MM-DD")
  );
  if (!current[0]) return false;
  return current[0];
};

/**
 * 根据当前排班内容获取对应的状态
 * @param duty 排班内容
 */
const getCurrentStatus = (duty: any) => {
  if (!duty) return "#b8beb9";
  const status = duty.reponStatus;
  const result = levelList.filter(({ value }: any) => value == status);
  return result[0];
};

const detail = reactive({
  open: false,
  data: {},
});

const handleDayClick = async (day: Dayjs) => {
  const current = getStatus(day);

  if (current) {
    // 存在值班状态
    const { reponStatus, id } = current;
    const { watchStaffDtoList } = await get("info", { id });
    let reponList = [];
    // 应急响应状态时
    if (["1", "2", "3", "4"].includes(reponStatus)) {
      // 详情表单展示响应人员表格
      detailFormMap.value = editFormMap.concat([
        {
          label: "响应人员",
          type: "table",
          prop: "reponList",
          columns: [
            {
              label: "姓名",
              prop: "name",
            },
            {
              label: "职位",
              prop: "position",
            },
            {
              label: "联系方式",
              prop: "phone",
            },
            {
              label: "岗位职责",
              prop: "job",
            },
          ],
        },
      ]);
      reponList = await get("getResponseList", { reponStatus });
    }

    detail.data = {
      date: day.format("YYYY-MM-DD"),
      phone: "1111-0000-000",
      reponStatus,
      watchStaffDtoList,
      reponList,
    };
  } else {
    detail.data = {
      date: day.format("YYYY-MM-DD"),
      phone: "1111-0000-000",
      reponStatus: 6,
      watchStaffDtoList: [],
    };
  }

  let securityList = undefined;
  const isToday =
    day.format("YYYY-MM-DD") == dayjs(Date()).format("YYYY-MM-DD");
  if (isToday && securityStatus.value) {
    detailFormMap.value = editFormMap.concat([
      {
        label: "亚运安保",
        type: "input",
        prop: "securityStatus",
      },
      {
        label: "安保人员",
        type: "table",
        prop: "securityList",
        columns: [
          {
            label: "姓名",
            prop: "staffName",
          },
          {
            label: "工作组",
            prop: "workingGroup",
            width: 120,
          },
          {
            label: "职位",
            prop: "--position",
            format: formatPosition,
          },
          {
            label: "联系方式",
            prop: "phone",
            width: 120,
          },
          {
            label: "岗位职责",
            prop: "securityJob",
            width: 100,
          },
        ],
      },
    ]);
    const { list: securityList } = await get("/watch/security/page", {
      limit: 1000,
      page: 1,
    });
    detail.data = {
      ...detail.data,
      securityStatus: "已启动",
      securityList: securityList.map((e: any) => ({
        ...e,
        securityJob: e.workingGroup,
      })),
    };
    console.log(detail.data);
  }
  detail.open = true;
};

const onDrawerClose = () => (detailFormMap.value = editFormMap);
</script>

<template>
  <section class="page">
    <header>
      <ProFrom
        layout="inline"
        ref="queryFormRef"
        :mapping="queryFormMap"
        :model-value="queryForm"
        :defaultCol="4"
        @submit="handleQuery()"
      >
        <ProButton
          @click="() => queryFormRef?.reset()"
          text="重置"
          icon="redoOutlined"
          class="mr-15px"
        />
        <ProButton
          @click="handleQuery"
          type="primary"
          text="查询"
          :loading="querying"
          icon="SearchOutlined"
        />
      </ProFrom>
    </header>
    <main>
      <menu class="flex-x-between">
        <div></div>
        <!-- 图例 -->
        <div class="flex-y-center">
          <div
            class="status-type flex-y-center"
            :style="{ color }"
            v-for="{ label, color } in levelLegendtList"
            :key="label"
          >
            {{ label }}
          </div>
        </div>
        <a-button danger class="absolute-tr" @click="openResponse">
          <template #icon> <alert-outlined /></template>
          应急响应</a-button
        >
        <a-modal
          centered
          destroyOnClose
          v-model:visible="response.open"
          title="应急响应"
          @ok="handelChangeResponse"
          okText="启动"
        >
          <a-radio-group class="pb-10px!" v-model:value="response.value">
            <a-radio
              :style="{ display: 'flex', marginTop: '10px', fontSize: '16px' }"
              v-for="{ id, responseLevel, watchWarning } in response.levelList"
              :key="id"
              :value="id"
            >
              <span>{{ formatLevel(responseLevel) }}</span
              ><span class="text-14px ml-1em"
                >({{ watchWarning }})</span
              ></a-radio
            >
          </a-radio-group>
          <!-- <p class="mt-4 text-16px">{{ response.description }}</p> -->
        </a-modal>
      </menu>
      <a-calendar class="calendar">
        <template #headerRender="{ value, onChange }">
          <a-button
            @click="
              () => {
                let prevMonth = dayjs(value).subtract(1, 'months');
                onChange(prevMonth);
              }
            "
          >
            <template #icon><left-outlined /></template>
          </a-button>
          <span class="mx-10px text-blue">{{ value.format("M月") }}</span>
          <a-button
            @click="
              () => {
                let nextMonth = dayjs(value).add(1, 'months');
                onChange(nextMonth);
              }
            "
          >
            <template #icon><right-outlined /></template>
          </a-button>
        </template>
        <template #dateFullCellRender="{ current }">
          <code v-show="false">{{ (data = getStatus(current)) }}</code>
          <div
            class="day"
            :style="{
              background: getCurrentStatus(data)?.color?.replace(')', ',0.4)'),
              borderLeft: getCurrentStatus(data)?.color
                ? `5px solid ${getCurrentStatus(data)?.color}`
                : '3px solid #b8beba',
            }"
            @click="handleDayClick(current)"
          >
            <!-- 定义临时变量方便模板块中复用 -->
            <template v-if="data">
              <div class="full">
                <header class="flex-x-between">
                  <b>{{ current.date() }}</b>

                  <p
                    class="text-12px font-bold"
                    v-if="getCurrentStatus(data)?.label == '正常'"
                    :style="{ color: getCurrentStatus(data)?.color }"
                  >
                    正常
                  </p>
                  <p
                    v-else
                    class="text-12px font-bold"
                    :style="{
                      color: getCurrentStatus(data)?.color,
                    }"
                  >
                    {{ getCurrentStatus(data)?.label }}
                  </p>
                </header>
                <main class="flex-center">
                  <p class="ellipsis">值班干部: {{ data.officerDutyName }}</p>
                </main>
              </div>
            </template>
            <template v-else>
              <!-- 未排班 -->
              <span>{{ current.date() }}</span>
            </template>
          </div>
        </template>
      </a-calendar>
    </main>
    <a-drawer
      v-model:visible="detail.open"
      @close="onDrawerClose"
      destroyOnClose
      title="详情"
      width="680"
    >
      <ProFrom
        ref="editFormRef"
        :mapping="detailFormMap"
        :model-value="detail.data"
        :readonly="true"
      />
    </a-drawer>
  </section>
</template>

<style lang="less" scoped>
.calendar {
  max-height: calc(100vh - 300px);
  overflow: scroll;
  :deep(.ant-picker-calendar-header) {
    justify-content: start;
  }
  :deep(.ant-radio-group) {
    display: none;
  }
  :deep(.ant-picker-body th) {
    text-align: center;
    font-size: 18px;
    line-height: 40px;
    // border: 3px solid #b8beba;
  }

  // 隐藏本月以外的日期
  :deep(.ant-picker-body .ant-picker-cell:not(.ant-picker-cell-in-view)) {
    visibility: hidden;
  }
  :deep(.ant-picker-body th::before) {
    content: "周";
  }
}

.status-type {
  margin-right: 20px;
  &::before {
    content: "";
    display: block;
    margin-right: 5px;
    width: 15px;
    height: 15px;
    background-color: currentColor;
  }
}
// 单元格内容
.day {
  // height: 80px;
  height: 7vw;
  border: 1px solid #d9d9d9;
  // border-left: 4px solid currentColor;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  // opacity: 0.8;
  header {
    color: #000;
  }
}
</style>
